use cmsis_rtos2_rs::os_delay;

use super::{driver::{ctrl, sensor}, HeatErr};


//pub mod draw;
pub mod draw_water;


pub unsafe fn init() {
   // draw::init();
}

pub fn clamp_open() -> Result<(), HeatErr> {
   ctrl::clamp_valve_close();
   os_delay(500);
   ctrl::air_pump_open();
   
   let mut time_count = 0;
   loop {
      if sensor::is_clamp_right() {
         break;
      }
      os_delay(20);
      time_count += 20;
      if time_count >= 10 * 1000 {
         return Err(HeatErr::ClampOpenTimeout);
      }
   }
   Ok(())
}

pub fn clamp_close() -> Result<(), HeatErr> {
   ctrl::clamp_valve_open();
   os_delay(500);
   ctrl::air_pump_open();

   let mut time_count = 0;
   loop {
      if sensor::is_clamp_left() {
         break;
      }
      os_delay(20);
      time_count += 20;
      if time_count >= 10 * 1000 {
         return Err(HeatErr::ClampCloseTimeout);
      }
   }
   Ok(())
}

pub fn trun_move() -> Result<(), HeatErr> {
   ctrl::trun_valve_open();
   os_delay(500);
   ctrl::air_pump_open();
   
   let mut time_count = 0;
   loop {
      if sensor::is_trun_right() {
         break;
      }
      os_delay(20);
      time_count += 20;
      if time_count >= 10 * 1000 {
         return Err(HeatErr::TrunMoveTimeout);
      }
   }
   Ok(())
}

pub fn trun_reset() -> Result<(), HeatErr> {
   ctrl::trun_valve_close();
   os_delay(500);
   ctrl::air_pump_open();
   
   let mut time_count = 0;
   loop {
      if sensor::is_trun_left() {
         break;
      }
      os_delay(20);
      time_count += 20;
      if time_count >= 10 * 1000 {
         return Err(HeatErr::TrunResetTimeout);
      }
   }
   Ok(())
}

